/* 
 * Copyright 2009 Kazuhiro Sera. 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0 
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
 * either express or implied. See the License for the specific language 
 * governing permissions and limitations under the License. 
 */

package org.lightdi.util;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

/**
 * ArrayUtil<br>
 * <br>
 * 
 * @author Kazuhiro Sera
 * @version 1.0
 */

public class ArrayUtil {

	@SuppressWarnings("unchecked")
	public static <T> T[] toArray(List<T> arg) {
		if (arg == null)
			return null;
		int len = arg.size();
		if (len <= 0)
			return null;
		Class<?> clazz = arg.get(0).getClass();
		T[] retArr = (T[]) Array.newInstance(clazz, len);
		for (int i = 0; i < len; i++)
			retArr[i] = arg.get(i);
		return retArr;
	}

	public static <T> List<T> toArrayList(T[] arg) {
		if (arg == null)
			return null;
		int len = arg.length;
		if (len <= 0)
			return null;
		List<T> retList = new ArrayList<T>();
		for (int i = 0; i < len; i++) {
			retList.add((T) arg[i]);
		}
		return retList;
	}

	@SuppressWarnings("unchecked")
	public static <T> T[] deepCopy(T[] arg) {
		if (arg == null)
			return arg;
		int len = arg.length;
		Class<?> clazz = arg[0].getClass();
		T[] retArr = (T[]) Array.newInstance(clazz, len);
		for (int i = 0; i < len; i++)
			retArr[i] = ObjectUtil.deepCopy(arg[i]);
		return retArr;
	}
}
